<?php
namespace app\index\controller;

use app\admin\model\MemberUser;
use app\admin\model\StudyLunbo;
use app\admin\model\StudyVideo;
use app\admin\model\StudyFile;
use app\admin\model\StudyVideoOrder;
use app\admin\model\StudyVideoOrderRecord;
use app\admin\model\Wxpay;
use app\admin\model\WxSet;
use think\Controller;

class Study extends Controller
{
    public function index(){
        //推荐视频
        $whereAA['video_groom']=1;
        $whereAA['video_state']=0;
        $whereAA['video_show']=0;
        $video= StudyVideo::where($whereAA)->order('video_sort desc,id desc')->select();
        foreach($video as $k=>$v){
            $video[$k]['video_createtime']=date('Y-m-d H:i',$v['video_createtime']);
        }

        //推荐音频
        $whereAB['video_groom']=1;
        $whereAB['video_state']=1;
        $whereAB['video_show']=0;
        $audio= StudyVideo::where($whereAB)->order('video_sort desc,id desc')->select();
        foreach($audio as $k=>$v){
            $audio[$k]['video_createtime']=date('Y-m-d H:i',$v['video_createtime']);
        }

        //推荐文件
        $whereAC['file_groom']=1;
        $file= StudyFile::where($whereAC)->order('file_createtime desc')->select();
        foreach($file as $k=>$v){
            $file[$k]['file_createtime']=date('Y-m-d H:i:s',$v['file_createtime']);
        }

        $data=array();
        $data['video']=$video;
        $data['audio']=$audio;
        $data['file']=$file;
        return json(['code'=>1,'data'=>$data]);
    }
    public function lunbo(){
        //首页轮播
        $data=StudyLunbo::order('lun_sort desc')->select();
        return json(['code'=>1,'data'=>$data]);
    }
    public function videoList(){
        $post=input('post.');
        $page=$post['pageid'];
        $whereAA['video_state']=0;
        $whereAA['video_show']=0;
        $video= StudyVideo::where($whereAA)->page($page,10)->order('video_sort desc,id desc')->select();
        if($video){
            foreach($video as $k=>$v){
                $video[$k]['video_createtime']=date('Y-m-d H:i',$v['video_createtime']);
            }
            return json(['code'=>1,'msg'=>'数据返回成功','data'=>$video]);
        }else{
            return json(['code'=>0,'msg'=>'没有数据']);
        }
    }
    public function audioList(){
        $post=input('post.');
        $page=$post['pageid'];
        $whereAA['video_state']=1;
        $whereAA['video_show']=0;
        $video= StudyVideo::where($whereAA)->page($page,10)->order('video_sort desc,id desc')->select();
        if($video){
            foreach($video as $k=>$v){
                $video[$k]['video_createtime']=date('Y-m-d H:i',$v['video_createtime']);
            }
            return json(['code'=>1,'msg'=>'数据返回成功','data'=>$video]);
        }else{
            return json(['code'=>0,'msg'=>'没有数据']);
        }
    }
    //音视频详情
    public function audioVideoCon(){
        $post=input('post.');
        $whereAA['id']=$post['id'];
        $video= StudyVideo::where($whereAA)->find();
        if($video){
            $video['video_createtime']=date('Y-m-d H:i',$video['video_createtime']);
            return json(['code'=>1,'msg'=>'数据返回成功','data'=>$video]);
        }
        else{
            return json(['code'=>0,'msg'=>'没有数据']);
        }
    }
    public function fileList(){
        $post=input('post.');
        $page=$post['pageid'];
        $file= StudyFile::page($page,20)->order('file_createtime desc')->select();

        if($file){
            foreach($file as $k=>$v){
                $file[$k]['file_createtime']=date('Y-m-d H:i:s',$v['file_createtime']);
            }
            return json(['code'=>1,'msg'=>'数据返回成功','data'=>$file]);
        }else{
            return json(['code'=>0,'msg'=>'没有数据']);
        }
    }
    public function fileCon(){
        $post=input('post.');
        $whereAA['id']=$post['id'];
        $file= StudyFile::where($whereAA)->find();
        if($file){
            $file['file_createtime']=date('Y-m-d H:i',$file['file_createtime']);
            return json(['code'=>1,'msg'=>'数据返回成功','data'=>$file]);
        }
        else{
            return json(['code'=>0,'msg'=>'没有数据']);
        }
    }
    //点击立即学习
    public function clickStudy(){
        $post=input('post.');
        $whereAA['user_id']=$post['user_id'];
        $whereAA['video_id']=$post['id'];
        $order=StudyVideoOrder::where($whereAA)->find();
        if($order){
            if($order['order_pay_state']==1){
                return json(['code'=>1,'msg'=>'已购买！']);
            }else{
                //请支付
                $whereAA['order_pay_state']=0;
                StudyVideoOrder::where($whereAA)->delete();

                $sub=$this->videoPay($post['user_id'],$post['id']);
                return json($sub);
            }
        }
        $sub=$this->videoPay($post['user_id'],$post['id']);
        return json($sub);
    }
    //音视频支付
    public function videoPay($user_id,$video_id){
        //查询音视频，获取金额
        $whereAA['id']=$video_id;
        $video=StudyVideo::where($whereAA)->find();
        if(!$video){
            return json(['code'=>0,'msg'=>'音视频不存在！']);
        }
        //查询用户，获取openid
        $whereAB['id']=$user_id;
        $user=MemberUser::where($whereAB)->find();
        if(!$user){
            return json(['code'=>0,'msg'=>'用户不存在！']);
        }
        $orderid=$this->randomStr().time();
        $data=[
            'user_id'=>$user_id,
            'openid'=>$user['open_id'],
            'video_id'=>$video_id,
            'orderid'=>$orderid,
            'order_price'=>$video['video_price'],
            'order_pay_state'=>0,
            'order_createtime'=>time()
        ];
        $save=StudyVideoOrder::insert($data);
        if($save){
            $url = 'https://'.$_SERVER['HTTP_HOST'];
            $notify_url = $url.'/index/Study/notify_url';
            $ret = WxSet::get(1);
            $appid = $ret['appID'];        //准备数据（都在后台系统中可查到）
            $mch_id = $ret['mch_id'];      //商户号
            $key = $ret['key'];

            $openid=$user['open_id'];
            $out_trade_no=$orderid;
            $total_fee=(int)($video['video_price']*100);

            $body='灯塔高校圈';
            $spbill_create_ip = request()->ip();


            $weixinpay = new Wxpay($appid, $openid, $mch_id, $key, $out_trade_no, $body, $total_fee, $notify_url, $spbill_create_ip);
            $return = $weixinpay->pay();

            return $return;
        }
        return ['code'=>0,'msg'=>'购买失败！'];
    }
    public function notify_url()
    {
        //获取接口数据，如果$_REQUEST拿不到数据，则使用file_get_contents函数获取

        $post = file_get_contents("php://input");
        libxml_disable_entity_loader(true); //禁止引用外部xml实体
        $xml = simplexml_load_string($post, 'SimpleXMLElement', LIBXML_NOCDATA);//XML转数组
        $post_data = (array)$xml;
        //订单号
        $out_trade_no = isset($post_data['out_trade_no']) && !empty($post_data['out_trade_no']) ? $post_data['out_trade_no'] : 0;
        //查询订单信息
        $order_info = StudyVideoOrder::where('orderid',$out_trade_no)->find();

        if ($order_info) {
            if ($post_data['return_code'] == 'SUCCESS'&&$post_data['result_code']== 'SUCCESS'){
                if($order_info['pay_callback']==0){
                    $whereAA['orderid']=$out_trade_no;
                    $data['pay_callback']=1;
                    $data['order_pay_state']=1;
                    $data['order_paytime']=time();
                    $data['transaction_id']=$post_data['transaction_id'];
                    StudyVideoOrder::where($whereAA)->update($data);

                    //支付成功，产品加销量
                    $orderRes=StudyVideoOrder::where($whereAA)->find();
                    $whereAB['id']=$orderRes['video_id'];
                    $videoRes=StudyVideo::where($whereAB)->find();
                    $datasales['video_sales']=$videoRes['video_sales']+1;
                    StudyVideo::where($whereAB)->update($datasales);

                    //回调成功，返给微信
                    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                }
            }
        }
    }
    //播放音视频
    public function videoStart(){
        $post=input('post.');

        //查询音视频
        $whereAA['id']=$post['id'];
        $video=StudyVideo::where($whereAA)->find();
        if(!$video){
            return json(['code'=>0,'msg'=>'音视频不存在！']);
        }
        //查询用户
        $whereAB['id']=$post['user_id'];
        $user=MemberUser::where($whereAB)->find();
        if(!$user){
            return json(['code'=>0,'msg'=>'用户不存在！']);
        }

        //学习改为学习中
        $whereAE['video_id']=$post['id'];
        $whereAE['user_id']=$post['user_id'];
        $dataab['study_state']=0;
        StudyVideoOrder::where($whereAE)->update($dataab);


        $whereAD['user_id']=$post['user_id'];
        $whereAD['video_id']=$post['id'];
        $find=StudyVideoOrderRecord::where($whereAD)->find();
        if($find){
            $data=[
                'user_id'=>$post['user_id'],
                'video_id'=>$post['id'],
                'video_time'=>$post['video_time'],
                'video_starttime'=>time()
            ];
            $save=StudyVideoOrderRecord::where($whereAD)->update($data);
        }else{
            $data=[
                'user_id'=>$post['user_id'],
                'video_id'=>$post['id'],
                'video_time'=>$post['video_time'],
                'video_starttime'=>time()
            ];
            $save=StudyVideoOrderRecord::insert($data);
        }
        if($save){
            return json(['code'=>1,'msg'=>'记录成功！']);
        }
        return json(['code'=>0,'msg'=>'记录失败！']);
    }
    //停止播放音视频
    public function videoEnd(){
        $post=input('post.');

        //查询音视频
        $whereAA['id']=$post['id'];
        $video=StudyVideo::where($whereAA)->find();
        if(!$video){
            return json(['code'=>0,'msg'=>'音视频不存在！']);
        }
        //查询用户
        $whereAB['id']=$post['user_id'];
        $user=MemberUser::where($whereAB)->find();
        if(!$user){
            return json(['code'=>0,'msg'=>'用户不存在！']);
        }

        $data['video_endtime']=$post['video_endtime'];
        $whereAD['user_id']=$post['user_id'];
        $whereAD['video_id']=$post['id'];
        $find=StudyVideoOrderRecord::where($whereAD)->find();

        $whereAE['video_id']=$post['id'];
        $whereAE['user_id']=$post['user_id'];

        //如果结束时间大于等于视频总时间，则为学习结束
        if($post['video_endtime']>=$find['video_time']){
            $dataab['study_state']=1;
            StudyVideoOrder::where($whereAE)->update($dataab);
        }

        if($find['video_endtime']==$post['video_endtime']){
            return json(['code'=>1,'msg'=>'记录成功！']);
        }
        $save=StudyVideoOrderRecord::where($whereAD)->update($data);
        if($save){
            return json(['code'=>1,'msg'=>'记录成功！']);
        }
        return json(['code'=>0,'msg'=>'记录失败！']);
    }
    //随机数
    public function randomStr(){
        $arr = array_merge(range(0,9),range('A','Z'));
        $str = '';
        $arr_len = count($arr);
        for($i = 0;$i < 8;$i++){
            $rand = mt_rand(0,$arr_len-1);
            $str.=$arr[$rand];
        }
        return $str;
    }
    //音视频学习列表
    public function videoOrderListAjax(){
        $post=input('post.');
        $page=$post['pageid'];
        $whereAA['order_pay_state']=1;
        $whereAA['user_id']=$post['user_id'];
        //学习中
        if($post['findtype']==1){
            $whereAA['study_state']=0;
        }
        if($post['findtype']==2){
            //已结束
            $whereAA['study_state']=1;
        }
        $data= StudyVideoOrder::where($whereAA)->page($page,10)->order('id desc')->select();

        if($data){
            foreach($data as $k=>$v){
                $data[$k]['order_createtime']=date('Y-m-d H:i:s',$v['order_createtime']);
                $data[$k]['order_paytime']=date('Y-m-d H:i:s',$v['order_paytime']);

                //查询音视频
                $whereAB['id']=$v['video_id'];
                $data[$k]['video']=StudyVideo::where($whereAB)->find();

                //查询用户
                $whereAC['id']=$v['user_id'];
                $data[$k]['user']=MemberUser::where($whereAC)->find();

                //查询学习记录
                $whereAD['video_id']=$v['video_id'];
                $whereAD['id']=$v['user_id'];
                $data[$k]['record']=StudyVideoOrderRecord::where($whereAD)->find();
                if($data[$k]['record']){
                    $data[$k]['record']['video_starttime']=date('Y-m-d H:i',$data[$k]['record']['video_starttime']);
                }
            }
            return json(['code'=>1,'msg'=>'返回成功','data'=>$data]);
        }else{
            return json(['code'=>0,'msg'=>'暂无数据！']);
        }
    }



}
